package com.open.party.cloud.view.home.article

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import cn.android.x.inters.AndroidView
import cn.android.x.model.data.AppPageData
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppTitleBaseActivity
import cn.android.x.plugins.webView.WebViewForFilePreviewActivity
import cn.sinothk.hussars.three.glide.ImageViewGlide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.jiangyy.easydialog.SingleChoiceDialog
import com.open.party.cloud.R
import com.open.party.cloud.ServerConfig
import com.open.party.cloud.model.ArticleEntity
import com.open.party.cloud.model.FileEntity
import com.open.party.cloud.model.TownshipBean
import com.open.party.cloud.model.data.LocalCache
import com.open.party.cloud.view.comm.data.Constants
import com.open.party.cloud.view.login.LoginActivity
import com.open.party.cloud.viewModel.ArticlePresent
import com.sinothk.android.utils.XUtils
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.article_details.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.ByteArrayOutputStream
import java.util.ArrayList


class ArticleDetailsActivity : AppTitleBaseActivity(), AndroidView<ResultInfo<AppPageData<ArticleEntity>>> {
    private var viewModel: ArticlePresent? = null

    override fun onDestroy() {
        super.onDestroy()
        //注销注册
        EventBus.getDefault().unregister(this)
    }

    var id = ""

    override fun getLayoutResId(): Int = R.layout.article_details

    private fun initWebView(data: ArticleEntity, webView: WebView) {
        val webSettings = webView.settings//获取webview设置属性
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN//把html中的内容放大webview等宽的一列中
        webSettings.javaScriptEnabled = true//支持js
        webSettings.setSupportZoom(false) // 可以缩放
        webSettings.blockNetworkImage = false;
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
//        webView.setInitialScale(70);   //100代表不缩放
        //扩大比例的缩放
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
//        webSettings.textSize = WebSettings.TextSize.LARGEST
//        webSettings.textZoom = 200
        //视频处理！
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;
        webSettings.loadsImagesAutomatically = true
        //
//        webSettings.builtInZoomControls = true
        webSettings.useWideViewPort = true;
        webSettings.loadWithOverviewMode = true;
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;

        val contentInfo = data.content

        webView.loadDataWithBaseURL(null, contentInfo, "text/html", "UTF-8", null)
        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if (newProgress < 100) {
                    progressView.visibility = View.VISIBLE
                    progressTv.text = "$newProgress %"
                } else {
                    progressView.visibility = View.GONE
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ArticlePresent(this)
        EventBus.getDefault().register(this)

        id = intent.getStringExtra("id") as String
        viewModel!!.getArticleDetail(id)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun receiveEventBus(resultInfo: ResultInfo<ArticleEntity>) {
        if ("getArticleDetail" == resultInfo.eventType) {
            when (resultInfo.code) {
                ResultInfo.SUCCESS -> {
                    setView(resultInfo.data)
                }
                ResultInfo.TOKEN_OVERDUE -> {
                }
                else -> {
                }
            }
        }
    }

    @SuppressLint("SetJavaScriptEnabled", "SetTextI18n")
    private fun setView(data: ArticleEntity?) {
        if (data == null) {
            return
        }

        setViewTitle(XUtils.string().getNotNullValue(data.childrenType.desc), R.drawable.share_icon_black) {
            if (!LocalCache.getAutoLogin()) {
                // 登录检测
                XUtils.intent().openActivity(this, LoginActivity::class.java).start()
                return@setViewTitle
            }

            shareToWx(data)
        }

        titleBarView.setCenterTxtColor(R.color.page_title)

        themeTv.text = XUtils.string().getNotNullValue(data.theme)
        pubDepTv.text = "${XUtils.string().getNotNullValue(data.ptSource)}"
//        browseTimesTv.text = "阅读量: ${data.browseTimes}"

        releaseTimeTv.text = XUtils.date().getFriendlyDate(data.releaseTime)

        reporterTv.text = "作者：${XUtils.string().getNotNullValue(data.reporter, "匿名")}"

        initWebView(data, webView)

        showFile(data.showList)
    }

    private fun showFile(fileList: ArrayList<FileEntity>?) {
        if (fileList != null && fileList.size > 0) {
            fileView.visibility = View.VISIBLE
            fileListView.setData(fileList) { entity ->
                WebViewForFilePreviewActivity.start(this@ArticleDetailsActivity, entity.fileName, ServerConfig.getFilePreviewUrl(entity.filePath))
            }
        } else {
            fileView.visibility = View.GONE
        }
    }

    override fun loadingShow() {
    }

    override fun loadingDismiss() {
    }

    override fun showTip(msg: String?) {
    }

    override fun complete(data: ResultInfo<AppPageData<ArticleEntity>>?) {
    }

    private fun shareToWx(article: ArticleEntity) {

        var shareBitmap: Bitmap? =
            BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_wx)
//        data.imgUrl = "https://upload.jianshu.io/users/upload_avatars/1687654/0679637b-6ad3-4343-8c92-8641fcf0b869.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/240/h/240"
        if (XUtils.string().isNotEmpty(article.imgUrl)) {
            ImageViewGlide.showForBitmap(
                applicationContext,
                article.imgUrl,
                object : CustomTarget<Bitmap>() {
                    override fun onLoadCleared(placeholder: Drawable?) {
                    }

                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        shareBitmap = resource
                    }
                })
        }

        SingleChoiceDialog.Builder(this).setTitle("信息分享")
            .addList(arrayOf("分享到朋友圈", "分享给微信好友"))
            .setOnItemClickListener { title, _ ->

                val titleStr = XUtils.string().getNotNullValue(article.theme)
                val descStr = XUtils.string().getNotNullValue(article.childrenType.desc)
                val url = ServerConfig.getArticleInfoUrl(article.id)

                val scene = if (title == "分享给微信好友") {
                    SendMessageToWX.Req.WXSceneSession
                } else {
                    SendMessageToWX.Req.WXSceneTimeline
                }
                shareWebPage(titleStr, descStr, url, scene, shareBitmap!!)
            }.show()
    }

    //    private var api: IWXAPI? = null
    private fun shareWebPage(title: String, desc: String, url: String, scene: Int, thumbBmp: Bitmap) {

        val api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false)

        //初始化一个WXWebpageObject，填写url
        val webpage = WXWebpageObject()
        webpage.webpageUrl = url    //"https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Share_and_Favorites/Android.html"

        //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
        val msg = WXMediaMessage(webpage)
        msg.title = title
        msg.description = desc

//        val thumbBmp: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_wx)
        msg.thumbData = units(thumbBmp)

        //构造一个Req
        val req: SendMessageToWX.Req = SendMessageToWX.Req()
        req.transaction = buildTransaction("webpage")
        req.message = msg
        req.scene = scene

        //调用api接口，发送数据到微信
        api.sendReq(req)
    }

    private fun units(thumbBmp: Bitmap): ByteArray? {
        //Bitmap转换成byte[]
        val baos = ByteArrayOutputStream();
        thumbBmp.compress(Bitmap.CompressFormat.JPEG, 30, baos);
        return baos.toByteArray();
    }


    private fun buildTransaction(type: String?): String? {
        return if (type == null) System.currentTimeMillis().toString() else type + System.currentTimeMillis()
    }
}
